package cc.aiee.demo.springboot.controller.chinapay;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cc.aiee.chinapay.api.ChinaPayApi;
import cc.aiee.chinapay.config.ChinaPayConfigKit;
import cc.aiee.chinapay.model.ChinaPayPaymentModel;
import cc.aiee.chinapay.model.ChinaPayRefundModel;
import cc.aiee.core.bean.R;
import cc.aiee.core.kit.KitId;
import cc.aiee.core.kit.KitIp;
import cc.aiee.demo.springboot.basic.constant.ContentType;
import cc.aiee.demo.springboot.basic.constant.ResultConst;
import cc.aiee.demo.springboot.controller.chinapay.bean.ChinaPayPaymentQuery;
import cc.aiee.demo.springboot.controller.chinapay.bean.ChinaPayRefundQuery;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/chinapay")
@Tag(name = "银联电子支付(china pay)")
@Slf4j
public class ChinaPayController {

	@Autowired
	private HttpServletRequest request;

	@PostMapping(value = "/payment", consumes = { ContentType.FORM, ContentType.JSON })
	@Operation(summary = "支付接口")
	public @ResponseBody R<Map<String, String>> create(ChinaPayPaymentQuery trans) {
		ChinaPayApi api = new ChinaPayApi();

		log.info("ChinaPay支付接口入参:{}", trans.toJson(true, true));
		ChinaPayPaymentModel model = trans.model(new ChinaPayPaymentModel());

		model.setRemoteAddr(KitIp.getRealIp(request));
		model.setMerOrderNo(KitId.timeId());
//		model.setOrderAmt("1");
		R<Map<String, String>> create = api.create(model, ChinaPayConfigKit.config);
		return create;
	}

	@PostMapping(value = "/payment/notify")
	@Operation(summary = "支付回调",hidden = true)
	public @ResponseBody String notify(HttpServletRequest request) {
		ChinaPayApi api = new ChinaPayApi();
		api.createNotify(request);
		return ResultConst.SUCCESS;
	}

	@PostMapping(value = "/refund", consumes = { ContentType.FORM, ContentType.JSON })
	@Operation(summary = "退款")
	public @ResponseBody R<Map<String, String>> refund(ChinaPayRefundQuery query) {
		ChinaPayApi api = new ChinaPayApi();

		ChinaPayRefundModel model = query.model(new ChinaPayRefundModel());
		api.openSandBox(true);
		model.setMerOrderNo(KitId.timeId());
		return api.refund(model, ChinaPayConfigKit.config);
	}

	@PostMapping(value = "/refund/notify")
	@Operation(summary = "退款回调",hidden = true)
	public @ResponseBody String refundnotify(HttpServletRequest request) {
		ChinaPayApi api = new ChinaPayApi();
		api.refundNotify(request);
		return ResultConst.SUCCESS;
	}
}
